package com.hello;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;

public class SettingScreen extends PreferenceActivity {
	static final int TIME_DIALOG_ID = 0;
	private PreferenceScreen screen;

//	private Preference time;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.settings);
		//	Preference fbu = (Preference) findPreference("facebookUser");
		screen = getPreferenceScreen();
		SharedPreferences pref = screen.getSharedPreferences();
		//schedule
		String t = pref.getString("prefsTime","23:00");
        screen.findPreference("prefsTime").setTitle("From" + "  " + t);
        screen.findPreference("prefsTaxi").setTitle(pref.getString("prefsTaxi",DrunkoidSettingData.getInstance().getTaxiPhone()));
		screen.findPreference("prefsTime").setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(final Preference preference) {
				String t = screen.getSharedPreferences().getString("prefsTime","23:00");				
				TimePicker.setTime(t);
				Intent myIntent = new Intent(getApplicationContext(), TimePicker.class);
				startActivityForResult(myIntent, 1);
				return true;
			}
		});
		screen.findPreference("prefsTaxi").setOnPreferenceChangeListener(new OnPreferenceChangeListener(){
			@Override
			public boolean onPreferenceChange(Preference preference,
					Object newValue) {
				screen.findPreference("prefsTaxi").setTitle((CharSequence) newValue);
				return true;
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case 1:
			if (resultCode == RESULT_OK){
				Editor editor = screen.findPreference("prefsTime").getEditor();
				editor.putString("prefsTime", TimePicker.getTime());
				editor.commit();
				screen.findPreference("prefsTime").setTitle( 
						"From" + "  " +
						TimePicker.getTime());
				Intent serviceIntent = new Intent();
				serviceIntent.setAction("com.hello.Launcher.AutoLauncherService");
				serviceIntent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
				stopService(serviceIntent);
				startService(serviceIntent);
			}
			break;
		default:
			super.onActivityResult(requestCode, resultCode, data);
			break;
		}
	}
}